package com.zzz.framework.config.mybatis;

import com.mybatisflex.core.FlexGlobalConfig;
import com.mybatisflex.core.dialect.IDialect;
import com.mybatisflex.core.logicdelete.AbstractLogicDeleteProcessor;
import com.mybatisflex.core.table.TableInfo;

import static com.mybatisflex.core.constant.SqlConsts.EQUALS;
import static com.mybatisflex.core.constant.SqlConsts.SINGLE_QUOTE;

/**
 * 自定义逻辑删除
 *
 * @see com.mybatisflex.core.logicdelete.impl.DefaultLogicDeleteProcessor
 */
public class MyLogicDeleteProcessor extends AbstractLogicDeleteProcessor {

    @Override
    public String buildLogicNormalCondition(String logicColumn, TableInfo tableInfo, IDialect dialect) {
        return dialect.wrap(logicColumn) + EQUALS + prepareValue(tableInfo, getLogicNormalValue(), false);
    }

    @Override
    public String buildLogicDeletedSet(String logicColumn, TableInfo tableInfo, IDialect dialect) {
        String sql = dialect.wrap(logicColumn) + EQUALS + prepareValue(tableInfo, getLogicDeletedValue(), true);
        //逻辑删除时设置删除时间
        sql += "," + dialect.wrap("deleted_time") + EQUALS + "now()";
        return sql;
    }

    @Override
    public Object getLogicNormalValue() {
        return FlexGlobalConfig.getDefaultConfig().getNormalValueOfLogicDelete();
    }

    @Override
    public Object getLogicDeletedValue() {
        return FlexGlobalConfig.getDefaultConfig().getDeletedValueOfLogicDelete();
    }

    private static Object prepareValue(TableInfo tableInfo, Object value, boolean isDeleted) {
        TableLogic anno = tableInfo.getEntityClass().getAnnotation(TableLogic.class);
        if (anno != null) {
            value = isDeleted ? anno.logicDeletedValue() : anno.logicNormalValue();
        }
        if (value instanceof Number || value instanceof Boolean) {
            return value;
        }
        return SINGLE_QUOTE + value + SINGLE_QUOTE;
    }
}
